package com.link.base.base.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.link.base.base.message.push.service.PushService;
import com.link.base.base.order.model.*;
import com.link.base.base.order.service.*;
import com.link.base.core.basic.util.YmlConstants;
import com.link.base.user.model.CoreUser;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.agreement.model.Agreement;
import com.link.base.base.agreement.service.AgreementService;
import com.link.base.base.approval.exception.ApprovalNeedUserException;
import com.link.base.base.order.model.*;
import com.link.base.base.order.service.*;
import com.link.base.base.orgnization.service.OrgnizationService;
import com.link.base.base.policy.service.PolicyService;
import com.link.base.base.product.model.ShopCart;
import com.link.base.base.product.service.PriceService;
import com.link.base.base.product.service.ShopCartService;
import com.link.base.base.receiptrecord.model.ReceiptRecord;
import com.link.base.base.receiptrecord.service.ReceiptRecordService;
import com.link.core.basic.service.snowflake.GenerateCodeSingleton;
import com.link.core.basic.service.snowflake.KeyGenerateUtil;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.*;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author unknown
 * @date unknown
 * @comments 定单请求处理
 */
@Controller
@RequestMapping("/link/saleorder")
public class SaleOrderController extends BasicController<SaleOrder> {
    @Resource
    private ApiSaleOrderService apiSaleOrderService;

    @Resource
    private SaleOrderService saleOrderService;

    @Resource
    private SaleOrderItemService saleOrderItemService;

    @Resource
    private AgreementService agreementService;

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private AccountService accountService;

    @Resource
    private OrderPolicyService orderPolicyService;

    @Resource
    private ShopCartService shopCartService;

    @Resource
    private PushService pushService;

    @Resource
    private PayRecordService payRecordService;

    @Resource
    private ReceiptRecordService receiptRecordService;

    //使用GenerateCodeSingleton获取订单编号
    GenerateCodeSingleton generateCodeSingleton = GenerateCodeSingleton.getInstance();

    /**
     * 政策
     */
    @Resource
    private PolicyService policyService;
    @Resource
    private OrgnizationService orgnizationService;

    @Resource
    private PriceService priceService;

    @Resource
    private JdbcTemplate jdbcTemplate;

    private static final Pattern PATTERN = Pattern.compile("(?<=\\[)([^\\(^\\)]+?)(?=\\])");

    /**
     * 按照List中的某个int/double类型的属性进行排序(按照省份总销量排序)
     *
     * @param list
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void sortDoubleMethod(List list) {
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                SaleOrder s1 = (SaleOrder) o1;
                SaleOrder s2 = (SaleOrder) o2;
                if (s1.getOrderTotalAmount() < s2.getOrderTotalAmount()) {
                    return 1;
                } else if (s1.getOrderTotalAmount().equals(s2.getOrderTotalAmount())) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
    }

    /**
     * 按照List中的某个int类型的属性进行排序 (按照省份订单数排序)
     *
     * @param list
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void sortIntMethod(List list) {
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                SaleOrder s1 = (SaleOrder) o1;
                SaleOrder s2 = (SaleOrder) o2;
                if (s1.getTotal() < s2.getTotal()) {
                    return 1;
                } else if (s1.getTotal().equals(s2.getTotal())) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
    }

    @Override
    public BasicService<SaleOrder> getBasicService() throws Exception {
        return saleOrderService;
    }

    @RequestMapping(value = "/init")
    public String init(QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {

        SaleOrder saleOrder = new SaleOrder();
        saleOrder.setId(keyGenerateService.keyGenerate());
        saleOrder.setStatus("New");
//        saleOrder.setOrderNo(saleOrder.getId().toString());
        saleOrder.setOrderNo(generateCodeSingleton.getOrderCodeStr());
        saleOrder.setOrderTypeLovType("05");
        try {
            saleOrder.setOrderType(LovUtil.getLovName("ORDER_TYPE", "05"));
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        CoreUser user = UserUtil.getUser();
        saleOrder.setCreatedByName(user.getFirstName());
        //标记
        saleOrder.setRow_status("NEW");
        request.setAttribute("saleOrder", saleOrder);
        return "order/InterSaleOrderInfoNew";
    }

    @RequestMapping(value = "/applyPolicyOne")
    @ResponseBody
    public Map<String, Object> applyPolicyInfo1(Long orderId, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (orderId == null) {
                throw new BasicControllerException("订单ID不能为空！");
            }
            SaleOrder example = new SaleOrder();
            example.setId(orderId);
            SaleOrder saleOrder = saleOrderService.queryById(example);
            if (saleOrder == null) {
                throw new BasicControllerException("未查到该订单，请刷新页面后重新操作！");
            }
            saleOrderService.applyPolicy(saleOrder);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/applyPolicyTwo")
    @ResponseBody
    public Map<String, Object> applyPolicyTwo(Long orderId, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (orderId == null) {
                throw new BasicControllerException("订单ID不能为空！");
            }
            SaleOrder example = new SaleOrder();
            example.setId(orderId);
            SaleOrder saleOrder = saleOrderService.queryById(example);
            if (saleOrder == null) {
                throw new BasicControllerException("未查到该订单，请刷新页面后重新操作！");
            }
            saleOrderService.applyPolicyTwo(saleOrder);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * <p>新建订单，返回初始化订单对象，用于弹出窗新建订单</p>
     *
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     * @author yrf
     */
    @RequestMapping(value = "/initNew")
    @ResponseBody
    public Map<String, Object> initNew(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            SaleOrder saleOrder = new SaleOrder();
            saleOrder.setId(keyGenerateService.keyGenerate());
            saleOrder.setStatus("New");
//            saleOrder.setOrderNo(saleOrder.getId().toString());
            saleOrder.setOrderNo(generateCodeSingleton.getOrderCodeStr());
            saleOrder.setOrderTypeLovType("05");
            try {
                saleOrder.setOrderType(LovUtil.getLovName("ORDER_TYPE", "05"));
            } catch (Exception e) {
                LCLogger.withException(e);
            }
            CoreUser user = UserUtil.getUser();
            saleOrder.setCreatedByName(user.getFirstName());
            //标记
            saleOrder.setRow_status("NEW");
            result.put("success", true);
            result.put("result", saleOrder);
            return result;
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/newInnerNotice", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> newInnerNotice(@JsonParam SaleOrder record, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            SaleOrder saleOrder = new SaleOrder();
            saleOrder.setId(keyGenerateService.keyGenerate());
            saleOrder.setOrderNoticeId(saleOrder.getId());
            saleOrder.setCreatedByName(user.getFirstName());
            saleOrder.setOrderNoticeType("Domestic Order");
            result.put("success", true);
            result.put("result", saleOrder);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/newOuterNotice", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> newOuterNotice(@JsonParam SaleOrder record, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            SaleOrder saleOrder = new SaleOrder();
            saleOrder.setId(keyGenerateService.keyGenerate());
            saleOrder.setOrderNoticeId(saleOrder.getId());
            saleOrder.setCreatedByName(user.getFirstName());
            saleOrder.setOrderNoticeType("International Order");
            result.put("success", true);
            result.put("result", saleOrder);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 深度复制头和行
     */
    @RequestMapping(value = "/copy/{id}")
    public String Copy(@PathVariable Long id, QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        CoreUser user = UserUtil.getUser();
        SaleOrder record = new SaleOrder();
        try {
            SaleOrder queryOrder = new SaleOrder();
            queryOrder.setId(id);
            record = saleOrderService.queryById(queryOrder);
            //record.setHeadId(id);
            if (record.getId() == null || "".equals(record.getId())) {
                qps.addFilter(new Filter("headId", "noMatchId"));
            } else {
                qps.addFilter(new Filter("headId", String.valueOf(id)));
            }
            qps.setPageFlag(false);
            SaleOrderItem t = (SaleOrderItem) BasicModel.transformClass(SaleOrderItem.class, qps);
            t.setId(null);
            List<SaleOrderItem> list = saleOrderItemService.queryByExamplePage(t);
            record.setId(keyGenerateService.keyGenerate());
            for (SaleOrderItem saleOrderItem : list) {
                saleOrderItem.setId(keyGenerateService.keyGenerate());
                saleOrderItem.setQty(1.0);
                saleOrderItem.setHeadId(record.getId());
                saleOrderItemService.insert(saleOrderItem);
            }
//            record.setOrderNo(record.getId().toString());
            record.setOrderNo(generateCodeSingleton.getOrderCodeStr());
            record.setStatus("New");
            record.setCreatedByName(user.getFirstName());
            //标记
            record.setRow_status("NEW");
            request.setAttribute("saleOrder", record);

        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return "order/InterSaleOrderInfoNew";
    }

    /**
     * 深度复制订单，返回订单头对象
     */
    @Override
    @RequestMapping(value = "/deepCopy")
    @ResponseBody
    public Map<String, Object> deepCopy(SaleOrder entity, HttpSession session,
                                        HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        CoreUser user = UserUtil.getUser();
        SaleOrder record = new SaleOrder();
        try {
            if (entity.getId() == null || "".equals(entity.getId())) {
                result.put("success", false);
                result.put("result", "参数错误，请输入需要复制的订单id");
                return result;
            }
            SaleOrder queryOrder = new SaleOrder();
            queryOrder.setId(entity.getId());
            record = saleOrderService.queryById(queryOrder);
            if (record == null) {
                result.put("success", false);
                result.put("result", "订单id【" + entity.getId() + "】的订单不存在");
                return result;
            }
            SaleOrderItem t = new SaleOrderItem();
            Long headId = (record.getId() == null || "".equals(record.getId())) ? Long.parseLong("noMatchId") : record.getId();
            t.setHeadId(headId);
            t.setPageFlag(false);
            t.setId(null);
            List<SaleOrderItem> list = saleOrderItemService.queryByExamplePage(t);
            record.setId(keyGenerateService.keyGenerate());
            for (SaleOrderItem saleOrderItem : list) {
                saleOrderItem.setId(keyGenerateService.keyGenerate());
                saleOrderItem.setQty(1.0);
                saleOrderItem.setHeadId(record.getId());
                saleOrderItemService.insert(saleOrderItem);
            }

//            record.setOrderNo(record.getId().toString());
            record.setOrderNo(generateCodeSingleton.getOrderCodeStr());
            record.setStatus("New");
            record.setCreatedByName(user.getFirstName());
            //标记
            record.setRow_status("NEW");
            result.put("success", true);
            result.put("result", record);
            return result;
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        //return "order/InterSaleOrderInfoNew";
        return result;
    }

    @RequestMapping(value = "/detail/{id}")
    public String detail(@PathVariable Long id, QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("detail")
                .withMessage(AppConstants.LOG_DIVISION_LINE + "saleOrder detail readonly init: saleOrderId is " + id).flush();
        SaleOrder saleOrder = new SaleOrder();
        try {
            SaleOrder queryOrder = new SaleOrder();
            queryOrder.setId(id);
            saleOrder = saleOrderService.queryById(queryOrder);
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        saleOrder.setRow_status("UPDATE");
        saleOrder.setHeadId(id);
        request.setAttribute("saleOrder", saleOrder);
        String newStatus = "New";
        if (newStatus.equals(saleOrder.getStatusLovType())) {
            return "order/InterSaleOrderInfoNew";
        }
        request.setAttribute("orderType", saleOrder.getOrderTypeLovType());
        return "order/SaleOrderInfoReadOnly";
    }

    @RequestMapping(value = "/commit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> commit(@JsonParam SaleOrder record, Long selectUserId, HttpSession session,
                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        try {
            saleOrderService.orderCommitUpdate(record, selectUserId);
            SaleOrder example = new SaleOrder();
            example.setId(record.getId());
            SaleOrder newRow = saleOrderService.queryById(example);
            result.put("newRow", newRow);
            result.put("success", true);
        } catch (ApprovalNeedUserException e) {
            LCLogger.withException(e);
//            Pattern pattern = Pattern.compile("(?<=\\[)([^\\(^\\)]+?)(?=\\])");
            Matcher match = PATTERN.matcher(e.getMessage());
            List<String> filedList = new ArrayList<String>();
            while (match.find()) {
                filedList.add(match.group());
            }
            result.put("success", false);
            result.put("mustSelectUser", true);
            result.put("userId", filedList.get(0));
            result.put("nodeId", filedList.get(1));
            result.put("result", "必须选择用户！");
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> cancel(@JsonParam SaleOrder record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            record.setStatus("Cancelled");
            saleOrderService.cancelSaleOrderUpdate(record);
            SaleOrder example = new SaleOrder();
            example.setId(record.getId());
            SaleOrder newRow = saleOrderService.queryById(example);
            result.put("newRow", newRow);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    @RequestMapping(value = "/sendComplete", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> sendComplete(@JsonParam SaleOrder record, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            //买方确认收货后即完成订单
            saleOrderService.confirmArrivedUpdate(record);
            saleOrderService.sendComplete(record);
            SaleOrder example = new SaleOrder();
            example.setId(record.getId());
            SaleOrder newRow = saleOrderService.queryById(example);
            result.put("newRow", newRow);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>设置订单状态为已审核</p>
     *
     * @param record
     * @param session
     * @param request
     * @param response
     * @return
     * @author yrf
     */
    @RequestMapping(value = "/approved", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> orderApproved(@JsonParam SaleOrder record, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            saleOrderService.orderApprovedUpdate(record);
            SaleOrder order = saleOrderService.queryById(record);
            if (order != null) {
                result.put("newRow", order);
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>设置订单状态为已发货</p>
     *
     * @param record
     * @param session
     * @param request
     * @param response
     * @return
     * @author yrf
     */
    @RequestMapping(value = "/shipped", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> orderShipped(@RequestBody SaleOrder record, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            saleOrderService.orderConfirmSendUpdate(record);
            SaleOrder order = saleOrderService.queryById(record);
            if (order != null) {
                result.put("newRow", order);
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    //取消掉必输控制
//    public void beforUpsert(SaleOrder record,HttpServletRequest request){
//        if(StringUtils.isNull(record.getAcctId())){
//            throw new BasicServiceException("客户名称不能为空！");
//        }
//        if(StringUtils.isNull(record.getAddrId())){
//            throw new BasicServiceException("收货地址不能为空！");
//        }
//        if(StringUtils.isNull(record.getExpectDate())){
//            throw new BasicServiceException("期望发货日期不能为空！");
//        }
//        if(StringUtils.isNull(record.getPayType())){
//            throw new BasicServiceException("支付方式不能为空！");
//        }
//    }

    /**
     * 更新定单
     */
    @RequestMapping(value = "/updateOrderAcctId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateOrderAcctId(@JsonParam SaleOrder record, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            saleOrderService.orderAcctIdUpdate(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/countTotalCash", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> countTotalCash(SaleOrder record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        Double total = 0.0;
        try {
            total = saleOrderService.countTotalCash(record);
            result.put("success", true);
            result.put("totalCash", total);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryTotalAmount")
    @ResponseBody
    public Map<String, Object> queryTotalAmount(SaleOrder record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        Double amount = 0.0;
        SaleOrder saleOrder = new SaleOrder();
        try {
            saleOrder = saleOrderService.querySaleOrderTotalAmount(record);
            amount = saleOrder.getOrderTotalAmount();
            result.put("success", true);
            result.put("amount", amount);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryDomesticNoticeListPage")
    @ResponseBody
    public Map<String, Object> queryDomesticNoticeListPage(@JsonParam QueryParams qps, @JsonParam SaleOrder entity, HttpSession session,
                                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.addFilter(new Filter("orderNoticeType", "Domestic Order"));
            qps.preDealSecurity(request);
            SaleOrder t = (SaleOrder) BasicModel.transformClass(entity.getClass(), qps);
            beforQueryAllOrExample(t, request);
            beforQueryExample(t, request);
            List<SaleOrder> list = getBasicService().queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", ((BasicModel) t).getTotal());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Agreement>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryIntlNoticeListPage")
    @ResponseBody
    public Map<String, Object> queryIntlNoticeListPage(@JsonParam QueryParams qps, @JsonParam SaleOrder entity,
                                                       HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.addFilter(new Filter("orderNoticeType", "International Order"));
            qps.preDealSecurity(request);
            SaleOrder t = (SaleOrder) BasicModel.transformClass(entity.getClass(), qps);
            beforQueryAllOrExample(t, request);
            beforQueryExample(t, request);
            List<SaleOrder> list = getBasicService().queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", ((BasicModel) t).getTotal());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Agreement>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/getContractId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getContractId(SaleOrder record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String contractCode = record.getContractCode();
            Agreement agreement = new Agreement();
            agreement.setAgrNumber(contractCode);
            List<Agreement> list = agreementService.queryByContractCode(agreement);
            if (list.size() == 1) {
                result.put("success", true);
                result.put("result", list.get(0));
            } else if (list.size() < 1) {
                result.put("success", false);
                result.put("result", "未查找到对应的合同审批记录！");
            } else {
                result.put("success", false);
                result.put("result", "查找到多条合同审批记录！");
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>经销商新建订单，保存订单产品信息步骤，地址信息等尚未完善</p>
     *
     * @param list
     * @param session
     * @param request
     * @param response
     * @return
     * @author yrf
     */
    @RequestMapping(value = "/newDmsOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> newDmsOrder(@RequestBody List<SaleOrderItem> list, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            Long acctId = user.getAcctId();
            if (acctId == null) {
                throw new ServiceException("ORDER-050");
            }
            if (list.size() <= 0) {
                throw new ServiceException("ORDER-085");
            }
            SaleOrder saleOrder = new SaleOrder();
            Long orderId = keyGenerateService.keyGenerate();
            saleOrder.setId(orderId);
            saleOrder.setAcctId(acctId);
            Account account = new Account();
            account.setId(acctId);
            //确认系统中确实有此客户才允许新建
            account = accountService.queryById(account);
            if (account == null) {
                throw new ServiceException("ORDER-050");
            }
            if (account.getPriceListId() == null) {
                throw new ServiceException("PUBLIC-056");
            }
//            saleOrder.setOrderNo(saleOrder.getId().toString());
            saleOrder.setOrderNo(generateCodeSingleton.getOrderCodeStr());
            saleOrder.setStatus("New");
            String flag = "Y";
            if (flag.equals(YmlConstants.getDmsForSiebel())) {
                //走siebel接口
                //SaleOrder entity = saleOrderService.insertByWS(saleOrder);
                //ssaleOrderItemService.insertDmsOrderItem(acctId, entity.getId(), list);
            } else {
                //走DB
                saleOrder.setPriceListId(account.getPriceListId());
                saleOrder.setOrgId(account.getOrgId());
                //利用行上的备用字段Attr7保存订单类型信息
                saleOrder.setOrderType(list.get(0).getAttr7());
                if (StringUtils.isBlank(saleOrder.getOrderType())) {
                    //默认销售订单
                    saleOrder.setOrderType("05");
                    saleOrder.setOrderTypeLovType("05");
                }
                saleOrderService.insert(saleOrder);
                saleOrderItemService.insertDmsOrderItem(null, acctId, orderId, list);
                String orderType = "05";
                if (orderType.equals(saleOrder.getOrderType())) {
                    //销售订单应用政策
                    // 应用政策，生成政策应用结果到订单下，并插入赠品行
                    orderPolicyService.applyPolicyOne(saleOrder);
                }
            }
            result.put("success", true);
            result.put("result", saleOrder);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>经销商修改订单行</p>
     *
     * @param list
     * @param session
     * @param request
     * @param response
     * @return
     * @author yrf
     */
    @RequestMapping(value = "/updateDmsOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateDmsOrder(@RequestBody List<SaleOrderItem> list, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            Long acctId = user.getAcctId();
            if (acctId == null) {
                throw new ServiceException("ORDER-050");
            }
            if (list.size() <= 0) {
                throw new Exception("ORDER-085");
            }
            Long orderId = list.get(0).getHeadId();
            SaleOrder order = new SaleOrder();
            order.setId(orderId);
            order = saleOrderService.queryById(order);
            if (order == null) {
                //查询不到原订单，重新新建一个
                return this.newDmsOrder(list, session, request, response);
            } else {
                saleOrderItemService.updateDmsOrderItem(acctId, orderId, list);
            }
            String flag = "Y";
            String orderType = "05";
            if (!flag.equals(YmlConstants.getDmsForSiebel())) {
                if (orderType.equals(order.getOrderType())) {
                    //销售订单应用政策
                    orderPolicyService.applyPolicyOne(order);
                }
            }

            result.put("result", order);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>经销商提交订单</p>
     *
     * @param order
     * @param session
     * @param request
     * @param response
     * @return
     * @author yrf
     */
    @RequestMapping(value = "/submitDmsOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> submitDmsOrder(SaleOrder order, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            Long acctId = user.getAcctId();
            if (acctId == null) {
                throw new ServiceException("ORDER-050");
            }
            if (order.getId() == null) {
                throw new ServiceException("PUBLIC-007");
            }
            if (!acctId.equals(order.getAcctId())) {
                throw new ServiceException("ORDER-086");
            }
            Account account = new Account();
            account.setId(acctId);
            //确认系统中确实有此客户才允许新建
            account = accountService.queryById(account);
            if (account == null) {
                throw new ServiceException("ORDER-050");
            }
            SaleOrder queryOrder = saleOrderService.queryById(order);
            String newStatus = "New";
            if (queryOrder == null) {
                throw new ServiceException("ORDER-087");
            } else if (!newStatus.equals(queryOrder.getStatus())) {
                throw new ServiceException("ORDER-088");
            }
            String flag = "Y";
            if (flag.equals(YmlConstants.getDmsForSiebel())) {
                order.setStatus("Submitted");
                order.setOrderNo(queryOrder.getOrderNo());
                //saleOrderService.updateByWS(order);//走订单更新接口
            } else {
                //queryOrder.setComments(order.getComments());
                order.setPriceListId(queryOrder.getPriceListId());
                order.setOrgId(queryOrder.getOrgId());
                Double rebateMoney = account.getRebatePercent() == null ? 0d : account.getRebatePercent() * queryOrder.getOrderTotalAmount();
                //返利金额
                order.setRebateMoney(rebateMoney);
                //现金金额
                order.setCash(queryOrder.getOrderTotalAmount() - rebateMoney);
                saleOrderService.update(order);
                String orderType = "05";
                if (orderType.equals(order.getOrderType())) {
                    //销售订单应用政策
                    orderPolicyService.applyPolicyTwo(order);
                }

                order.setStatus("Submitted");
                if (saleOrderService.orderStatusUpdate(order) != 1) {
                    //更改订单状态为已提交
                    throw new ServiceException("ORDER-087");
                }
            }

            //删除购物车记录，删除失败不影响订单数据，所以不报错
            String fromShopCart = "FromShopCart";
            try {
                if (fromShopCart.equals(order.getAttr1())) {
                    ShopCart shopCart = new ShopCart();
                    shopCart.setAttr1(String.valueOf(order.getId()));
                    shopCartService.deleteByOrderId(shopCart);
                }
            } catch (Exception e) {
                LCLogger.withException(e);
                result.put("result2", e.getMessage());
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>深度复制dms订单</p>
     *
     * @param order
     * @param session
     * @param request
     * @param response
     * @return
     * @author yrf
     */
    @RequestMapping(value = "/dmsDeepCopy")
    @ResponseBody
    public Map<String, Object> deepCopyDmsOrder(SaleOrder order, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            result.put("result",saleOrderService.deepCopyDmsOrder(order));
            result.put("success",true);
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            return result;
        }
    }

    /**
     * <p>经销商订单查询</p>
     *
     * @param session
     * @param request
     * @param response
     * @return
     * @author yrf
     */
    @RequestMapping(value = "/queryDmsOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryDmsOrder(@JsonParam QueryParams qps, @JsonParam SaleOrder order, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            Long acctId = UserUtil.getUser().getAcctId();
            if (acctId == null) {
                throw new ServiceException("ORDER-050");
            }

//          order = (SaleOrder)BasicModel.transformClass(order.getClass(), qps);//移动到下面
            //高级搜索，对下单时间的筛选
            String orderDateStart = request.getParameter("orderDateStart");
            String dataBase = "mysql";
            if (StringUtils.isNotBlank(orderDateStart)) {
                if (StringUtils.equals(YmlConstants.getApplicationDatabase(), dataBase)) {
                    Filter filter = new Filter("created",
                            Filter.OP_GREAT_EQUAL, "str_to_date('" + orderDateStart + " 00:00:00','%Y-%m-%d %H:%i:%S')");
                    filter.setStringTypeDateParam(true);
                    qps.addFilter(filter);
                } else {
                    qps.addFilter(new Filter("created", Filter.OP_GREAT_EQUAL, "to_date('" + orderDateStart + " 00:00:00','yyyy-mm-dd hh24:mi:ss')"));
                }
            }
            String orderDateEnd = request.getParameter("orderDateEnd");
            if (StringUtils.isNotBlank(orderDateEnd)) {
                if (StringUtils.equals(YmlConstants.getApplicationDatabase(), dataBase)) {
                    Filter filter = new Filter("created", Filter.OP_LESS_EQUAL, "str_to_date('" + orderDateEnd + " 23:59:59','%Y-%m-%d %H:%i:%S')");
                    filter.setStringTypeDateParam(true);
                    qps.addFilter(filter);
                } else {
                    qps.addFilter(new Filter("created", Filter.OP_LESS_EQUAL, "to_date('" + orderDateEnd + " 23:59:59','yyyy-mm-dd hh24:mi:ss')"));
                }
            }
            order = (SaleOrder) BasicModel.transformClass(order.getClass(), qps);

            //校验
            boolean vaildFlag = false;
            for (Filter f : qps.getFilters()) {
                String field = f.getProperty();
                String value = f.getValue();
                String op = f.getOperator();
                if (!Filter.OP_EQUAL.equalsIgnoreCase(op)) {
                    continue;
                }
                vaildFlag = true;
            }
            if (!vaildFlag) {
                throw new ServiceException("PUBLIC-003");
            }

            List<SaleOrder> list = saleOrderService.queryByExamplePage(order);
            result.put("rows", list);
            result.put("total", getCount((BasicModel) order, list.size()));
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询订单物流信息
     */
    @RequestMapping(value = "/logistics", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> logistics(SaleOrder order, HttpSession session, HttpServletRequest request,
                                         HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        LinkRedisClient j = RedisUtil.getJedis();
        try {
            SaleOrder o = saleOrderService.queryById(order);
            // Closed:已经关闭
            String status = o.getStatus();
            String logisticsNo = o.getLogisticsNo();
            String logisticsCompany = o.getLogisticsCompany();

            // 如果没有订单信息，则直接返回
            if (StringUtils.isNull(logisticsNo)) {
                result.put("success", false);
                result.put("result", "没有物流单号，无法查询物流信息！");
            } else {

                String logisticsInfo = j.get(logisticsNo);

                LCLogger.info().withMessageKey("logistics")
                        .withMessage("redis query logisticsInfo is :" + logisticsInfo).flush();
                if (StringUtils.isNull(logisticsInfo)) {

                    Map<String, String> map = HttpUtils.queryLogistics(logisticsNo, logisticsCompany);
                    result.put("success", Boolean.parseBoolean(map.get(AppConstants.LOGISTICS_SUCCESS)));
                    result.put("result", map.get(AppConstants.LOGISTICS_RESULT));

                    LCLogger.info().withMessageKey("logistics")
                            .withMessage(status).flush();
                    LCLogger.info().withMessageKey("logistics")
                            .withMessage(map.get(AppConstants.LOGISTICS_SUCCESS)).flush();

                    // 如果订单已经关闭，则插入物流信息
                    String closed = "Closed";
                    String trueStr = "true";
                    if (closed.equals(status) && trueStr.equals(map.get(AppConstants.LOGISTICS_SUCCESS))) {
                        j.set(logisticsNo, map.get(AppConstants.LOGISTICS_RESULT));
                        j.expire(logisticsNo, 720000);
                    }
                } else {
                    result.put("success", true);
                    result.put("result", logisticsInfo);
                }
            }

        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        } finally {
            RedisUtil.returnResource(j);
        }
        return result;
    }

    /**
     * 查询地区订单
     */
    @RequestMapping(value = "/querySalesOrderOfDistrict", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> querySalesOrderOfDistrict(@JsonParam QueryParams qps, @JsonParam SaleOrder order,
                                                         HttpSession session, HttpServletRequest request,
                                                         HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        Map<String, String> map = new HashMap<String, String>();
        //存放合并相同省后的数据
        List<SaleOrder> newList = new ArrayList<SaleOrder>();
        try {
            SaleOrder record = (SaleOrder) BasicModel.transformClass(SaleOrder.class, qps);
            record.setPageFlag(false);
            //按照总销量降序排序
//            record.setOrderByClause("total desc");
            List<SaleOrder> list = saleOrderService.querySalesOrderOfDistrictPage(record);

            //合并省份一样的数据
            for (int i = 0; i < list.size(); i++) {
                //获取省份
                String key = list.get(i).getProvince();
                String old = map.get(key);
                if (old != null) {
                    map.put(key, old + "," + (i));
                } else {
                    map.put(key, "" + (i));
                }
            }
            Iterator<String> it = map.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                String value = map.get(key);
                System.err.println(key + " 重复,行： " + value);
                String[] a = value.split(",");
                int sum = 0;
                for (int j = 0; j < a.length; j++) {
                    sum += list.get(Integer.valueOf(a[j])).getTotal();
                }
                SaleOrder newSaleOrder = new SaleOrder();
                newSaleOrder.setProvince(key);
                newSaleOrder.setTotal(sum);
                //得到新的集合
                newList.add(newSaleOrder);
            }
            //排序
            sortIntMethod(newList);
            //获取报表前端代码
            String html = saleOrderService.getSalesOrderReportHtml(newList);

            result.put("success", true);
            result.put("rows", newList);
            result.put("html", html);
            result.put("total", getCount((BasicModel) order, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 查询地区销量
     */
    @RequestMapping(value = "/querySalesOfDistrict", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> querySalesOfDistrict(@JsonParam QueryParams qps, @JsonParam SaleOrder order,
                                                    HttpSession session, HttpServletRequest request,
                                                    HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        Map<String, String> map = new HashMap<String, String>();
        //存放合并相同省后的数据
        List<SaleOrder> newList = new ArrayList<SaleOrder>();
        try {
            SaleOrder record = (SaleOrder) BasicModel.transformClass(SaleOrder.class, qps);
            record.setPageFlag(false);
            //按照总销量降序排序
//            record.setOrderByClause("orderTotalAmount desc");
            List<SaleOrder> list = saleOrderService.querySalesOfDistrictPage(record);
            //合并省份一样的数据
            for (int i = 0; i < list.size(); i++) {
                //获取省份
                String key = list.get(i).getProvince();
                String old = map.get(key);
                if (old != null) {
                    map.put(key, old + "," + (i));
                } else {
                    map.put(key, "" + (i));
                }
            }
            Iterator<String> it = map.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                String value = map.get(key);
                System.err.println(key + " 重复,行： " + value);
                String[] a = value.split(",");
                double sum = 0;
                for (int j = 0; j < a.length; j++) {
                    sum += list.get(Integer.valueOf(a[j])).getOrderTotalAmount();
                }
                SaleOrder newSaleOrder = new SaleOrder();
                newSaleOrder.setProvince(key);
                newSaleOrder.setOrderTotalAmount(sum);
                //得到新的集合
                newList.add(newSaleOrder);
            }
            //排序
            sortDoubleMethod(newList);
            //获取报表前端代码
            String html = saleOrderService.getSalesReportHtml(newList);

            /*for(int i=0; i < list.size(); i++){
                SaleOrder saleOrder = list.get(i);
                Map<String, Double> map = HttpUtils.getLngAndLat(saleOrder.getFullAddr());
                saleOrder.setAttr1(map.get("longtitude").toString());//经度
                saleOrder.setAttr2(map.get("latitude").toString());//纬度
                if( i==0 ){
                    saleOrder.setAttr3("10");//设置权重，销量最高的设置为最大权重
                }else{
                    Double count = saleOrder.getOrderTotalAmount()/list.get(0).getOrderTotalAmount()*10;
                    System.err.println(count);
                    saleOrder.setAttr3(String.valueOf(count));//设置权重，销量与最高销量倍数
                }
            }*/
            result.put("success", true);
            result.put("rows", newList);
            result.put("html", html);
            result.put("total", getCount((BasicModel) order, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * @param saleOrder 订单
     * @return Map
     */
    @RequestMapping(value = "/upsertHeadAndLine", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upsertHeadAndLine(@RequestBody SaleOrder saleOrder, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            SaleOrder order = saleOrderService.upsertHeadAndLine(saleOrder);
            result.put("success", true);
            result.put("order", order);

        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * DMS订单结算
     *
     * @param saleOrder 订单
     * @return Map
     */
    @RequestMapping(value = "/upsertHeadAndLineDms", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upsertHeadAndLineDms(@JsonParam SaleOrder saleOrder, HttpSession session,
                                                    HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            SaleOrder order = saleOrderService.upsertHeadAndLine(saleOrder);
            result.put("success", true);
            result.put("order", order);

        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryHeadAndLineById", method = RequestMethod.POST)
    @ResponseBody
    Map<String, Object> queryHeadAndLineById(@RequestBody SaleOrder saleOrder) {
        Map<String, Object> result = new HashMap<String, Object>();
        Long id = saleOrder.getId();
        try {
            if (null == id) {
                throw new ServiceException("PUBLIC-007");
            }
            SaleOrder saleOrderRet = saleOrderService.queryOneById(id);
            if (null != saleOrderRet) {
                List<SaleOrderItem> saleOrderItems = saleOrderItemService.querylistByOrderId(id);
                saleOrderRet.setSaleOrderItemList(saleOrderItems);
                //收款记录
                PayRecord queryParam = new PayRecord();
                queryParam.setHeadId(saleOrderRet.getId());
                queryParam.setOrderId(saleOrderRet.getId());
                queryParam.setPageFlag(false);
                List<PayRecord> payRecords = payRecordService.queryByExamplePage(queryParam);
                saleOrderRet.setPayRecordList(payRecords);
                //开票记录
                ReceiptRecord receiptRecordParam = new ReceiptRecord();
                receiptRecordParam.setOrderId(saleOrderRet.getId());
                receiptRecordParam.setPageFlag(false);
                List<ReceiptRecord> receiptRecords = receiptRecordService.queryByExamplePage(receiptRecordParam);
                if (receiptRecords.size() > 0) {
                    saleOrderRet.setIs_receipt("Y");
                } else {
                    saleOrderRet.setIs_receipt("N");
                }
                saleOrderRet.setReceiptRecordList(receiptRecords);
                //实收金额
                Double paidInAmount = payRecords.stream()
                        .mapToDouble(p -> Double.parseDouble(p.getAmount()))
                        .sum();
                saleOrderRet.setPaidInAmount(paidInAmount);
            }
            result.put("success", true);
            result.put("order", saleOrderRet);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * HuangLJ 订单确认，会校验订单可售权限，订单整的，库存，以及资金
     *
     * @param saleOrder 订单对象
     * @return Map
     */
    @RequestMapping(value = "/confirm", method = RequestMethod.POST)
    @ResponseBody
    Map<String, Object> orderConfirm(@RequestBody SaleOrder saleOrder) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            //订单确认
            String errMsg = saleOrderService.confirm(saleOrder);
            if (!StringUtils.isNull(errMsg)) {
                //如果确认返回的错误信息不为空，则表示已经报错。同时把订单信息返回
                result.put("success", false);
                result.put("result", errMsg);
                result.put("newRow", saleOrder);
            } else {
                result.put("success", true);
                result.put("result", saleOrder);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * HuangLJ 订单确认，会校验订单可售权限，订单整的，库存，以及资金
     *
     * @param saleOrder 订单对象
     * @return Map
     */
    @RequestMapping(value = "/dmsConfirm", method = RequestMethod.POST)
    @ResponseBody
    Map<String, Object> dmsOrderConfirm(@RequestBody SaleOrder saleOrder) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            //订单确认
            String errMsgRet = saleOrderService.dmsConfirm(saleOrder);
            if (!StringUtils.isNull(errMsgRet)) {
                //如果确认返回的错误信息不为空，则表示已经报错。同时把订单信息返回
                result.put("success", false);
                result.put("result", errMsgRet);
                result.put("newRow", saleOrder);
            } else {
                result.put("success", true);
                result.put("result", saleOrder);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 各类型订单的出库和入库操作
     *
     * @author 何启谦
     */
    @RequestMapping(value = "/outInInvtxn", method = RequestMethod.POST)
    @ResponseBody
    Map<String, Object> outInInvtxn(@RequestBody SaleOrder entity) {
        Map<String, Object> result = new HashMap<>();
        try {
            Long orderId = entity.getId();
            String invtxnType = entity.getAttr1();
            if (StringUtils.isBlank(invtxnType)) {
                throw new ServiceException("ORDER-089");
            }
            String purchasein = "purchasein";
            if (StringUtils.equals(invtxnType, purchasein)) {
                //采购入库的接口为"/arrivedOrderItem"
                throw new ServiceException("ORDER-090");
            }
            //获取实时的订单头对象
            SaleOrder saleOrder = saleOrderService.queryById(orderId);
            List<SaleOrderItem> orderItemList = saleOrderItemService.querylistByOrderId(orderId);
            //设置出入库的产品数量
            for (SaleOrderItem item : orderItemList) {
                item.setThisQty(item.getQty());
            }
            //订单发货日期标识
            String expectDate = entity.getExpectDate();
            if (!StringUtils.isBlank(expectDate)) {
                saleOrder.setExpectDate(expectDate);
            }
            saleOrderService.outInInvtxn(saleOrder, orderItemList, invtxnType);
            SaleOrder newEntry = saleOrderService.queryById(orderId);
            result.put("success", true);
            result.put("result", newEntry);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 各类型订单的出库和入库操作之后，对订单状态的操作
     *
     * @author  张宇浩
     * @time    2019-3-28 11:46:03
     */
    @RequestMapping(value = "/orderStatusUpdate", method = RequestMethod.POST)
    @ResponseBody
    Map<String, Object> orderStatusUpdate(@RequestBody SaleOrder entity) {
        Map<String, Object> result = new HashMap<>();
        try {
            //对象Row_id
            Long orderId = entity.getId();
            //对象待更新状态
            String status = entity.getStatus();

            SaleOrder saleOrder = saleOrderService.queryById(orderId);
            saleOrder.setStatus(status);
            saleOrderService.orderStatusUpdate(saleOrder);
            SaleOrder newEntry = saleOrderService.queryById(orderId);
            result.put("success", true);
            result.put("result", newEntry);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>到货确认:生成记录、生成或修改库存产品-生成或修改库存产品数量、修改订单状态</p>
     *
     * @param paramOrderItemList 订单行list
     * @author 何启谦
     */
    @RequestMapping(value = "/arrivedOrderItem", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> arrivedOrderItem(@RequestBody List<SaleOrderItem> paramOrderItemList) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (paramOrderItemList == null || paramOrderItemList.size() == 0) {
                throw new ServiceException("ORDER-020");
            }
            //确认到货(采购入库)
            String invtxnType = "purchasein";
            SaleOrder newEntry = saleOrderService.arrivedOrderItem(paramOrderItemList, invtxnType);
            result.put("success", true);
            result.put("result", newEntry);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * HuangLJ 订单审核，会校验订单可售权限，订单整的，库存，以及资金,
     * 修改订单状态为以提交
     *
     * @param record 订单对象
     * @return Map
     */
    @RequestMapping(value = "/orderCommit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> orderCommit(@RequestBody SaleOrder record, String selectUserId, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            saleOrderService.orderCommit(record);
            SaleOrder example = new SaleOrder();
            example.setId(record.getId());
            SaleOrder newRow = saleOrderService.queryById(example);
            List<SaleOrderItem> items = saleOrderItemService.querylistByOrderId(record.getId());
            newRow.setSaleOrderItemList(items);
            result.put("result", newRow);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * HuangLj 订单相关操作，包括订单提交，审核，取消，完成，发货
     * 可以直接通过这个方法调用，也可以分别调用各自的方法。
     *
     * @param record   订单记录
     * @param session  session
     * @param request  请求
     * @param response 响应
     * @return map
     */
    @RequestMapping(value = "/statusChange", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> statusChange(@RequestBody SaleOrder record, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String status = record.getStatus();
            switch (status) {
                case "Shipped":
                    //发货
                    saleOrderService.orderConfirmSendUpdate(record);
                    SaleOrder order = saleOrderService.queryById(record);
                    if (order != null) {
                        List<SaleOrderItem> items = saleOrderItemService.querylistByOrderId(record.getId());
                        order.setSaleOrderItemList(items);
                        result.put("result", order);
                    }
                    result.put("success", true);
                    break;

                case "Closed":
                    //完成
                    saleOrderService.complete(record);
                    SaleOrder saleOrderComplete = new SaleOrder();
                    saleOrderComplete.setId(record.getId());
                    SaleOrder newRowComplete = saleOrderService.queryById(saleOrderComplete);
                    List<SaleOrderItem> items = saleOrderItemService.querylistByOrderId(record.getId());
                    newRowComplete.setSaleOrderItemList(items);
                    result.put("result", newRowComplete);
                    result.put("success", true);
                    break;

                case "Rejected":
                    //拒绝
                    record.setStatus("Rejected");
                    saleOrderService.orderStatusUpdate(record);
                    SaleOrder saleOrderRejected = new SaleOrder();
                    saleOrderRejected.setId(record.getId());
                    SaleOrder newRowRejected = saleOrderService.queryById(saleOrderRejected);
                    List<SaleOrderItem> item2 = saleOrderItemService.querylistByOrderId(record.getId());
                    newRowRejected.setSaleOrderItemList(item2);
                    result.put("result", newRowRejected);
                    result.put("success", true);
                    pushService.pushInfoRightAway("", "订单【" + newRowRejected.getOrderNo() + "】已经拒绝！",
                        newRowRejected.getCreatedBy(), "order", newRowRejected.getId(), "Y", "Y");
                    break;

                case "Approved":
                    //订单审核
                    saleOrderService.orderVerify(record);
                    SaleOrder saleOrderVerify = new SaleOrder();
                    saleOrderVerify.setId(record.getId());
                    SaleOrder newRowVerify = saleOrderService.queryById(saleOrderVerify);
                    List<SaleOrderItem> item3 = saleOrderItemService.querylistByOrderId(record.getId());
                    newRowVerify.setSaleOrderItemList(item3);
                    result.put("success", true);
                    result.put("result", newRowVerify);
                    break;

                case "Submitted":
                    //提交
                    saleOrderService.orderCommit(record);
                    SaleOrder saleOrderCommit = new SaleOrder();
                    saleOrderCommit.setId(record.getId());
                    SaleOrder newRowCommit = saleOrderService.queryById(saleOrderCommit);
                    List<SaleOrderItem> item4 = saleOrderItemService.querylistByOrderId(record.getId());
                    newRowCommit.setSaleOrderItemList(item4);
                    result.put("result", newRowCommit);
                    result.put("success", true);
                    break;

                case "Cancelled":
                    //取消
                    record.setStatus("Cancelled");
                    saleOrderService.cancelSaleOrderUpdate(record);
                    //如果有使用到优惠券的话，改变优惠券状态，
                    saleOrderService.couponsUpdateStatus(record);
                    SaleOrder saleOrderCancelled = new SaleOrder();
                    saleOrderCancelled.setId(record.getId());
                    SaleOrder newRowCancelled = saleOrderService.queryById(saleOrderCancelled);
                    List<SaleOrderItem> item5 = saleOrderItemService.querylistByOrderId(record.getId());
                    newRowCancelled.setSaleOrderItemList(item5);
                    result.put("result", newRowCancelled);
                    result.put("success", true);
                    break;

                default:
                    result.put("result", "不支持的类型");
                    result.put("success", true);
                    LCLogger.info().withMessageKey("statusChange")
                            .withMessage("不支持的类型").flush();
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * HuangLj 订单完成
     *
     * @param record   订单记录
     * @param session  session
     * @param request  请求
     * @param response 相应
     * @return map
     */
    @RequestMapping(value = "/returnOrdUpdateStatus", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> returnOrdUpdateStatus(@RequestBody SaleOrder record, HttpSession session,
                                                     HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            saleOrderService.returnOrdUpdateStatus(record);
            SaleOrder example = new SaleOrder();
            example.setId(record.getId());
            SaleOrder newRow = saleOrderService.queryById(example);
            List<SaleOrderItem> items = saleOrderItemService.querylistByOrderId(record.getId());
            newRow.setSaleOrderItemList(items);
            result.put("result", newRow);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * HuangLj 退货单退款
     *
     * @param record   订单记录
     * @param session  session
     * @param request  请求
     * @param response 响应
     * @return map
     */
    @RequestMapping(value = "/returnOrderRefund", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> returnOrderRefund(@RequestBody SaleOrder record, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            saleOrderService.returnOrderRefund(record);
            SaleOrder example = new SaleOrder();
            example.setId(record.getId());
            SaleOrder newRow = saleOrderService.queryById(example);
            List<SaleOrderItem> items = saleOrderItemService.querylistByOrderId(record.getId());
            newRow.setSaleOrderItemList(items);
            result.put("result", newRow);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    public void beforeCancel(SaleOrder record) throws Exception {
        //如果已有收款记录且收款总额大于0，系统提示“请先进行退款！”，
        // 新建一条收款金额为负的收款记录之后，
        // 再次点击取消订单并确认，更新订单状态为【已取消】
        PayRecord queryParam = new PayRecord();
        queryParam.setHeadId(record.getId());
        queryParam.setOrderId(record.getId());
        queryParam.setPageFlag(false);
        List<PayRecord> payRecords = payRecordService.queryByExamplePage(queryParam);
        Double sum = payRecords.stream()
//              .filter(p -> p.getPayStatus() == "AlreadyPaid")
                .mapToDouble(p -> Double.parseDouble(p.getAmount()))
                .sum();
        if (sum > 0) {
            throw new RuntimeException("已支付金额为：" + sum + ",请确认是否需要先退款！");
        }
    }

    /**
     * @author song
     * 170512
     * 新建订单
     */
    @RequestMapping(value = "/orderPay", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> orderPay(@RequestBody SaleOrder record, HttpSession session,
                                        HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            saleOrderService.orderPayUpdate(record);
            result.put("success", true);
        } catch (Exception e) {
            try {
                saleOrderService.collectRecordUpdate(record);
            } catch (Exception ex) {
                LCLogger.withException(ex);
                result.put("success", false);
                result.put("message", ex.getMessage());
            }
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * @author lizt
     * 20170916
     * 导购助手提交订单
     */
    @RequestMapping(value = "/commitGuideOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> commitOrder(@RequestBody SaleOrder record, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            SaleOrder o = saleOrderService.commitOrder(record);
            result.put("result", o);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }


    /**
     * @author lizt
     * 20170916
     * 订单销量排名
     */
    @RequestMapping(value = "/orderSaleRank", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> orderSaleRank(OrderSaleRank record, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            OrderSaleRank osr = saleOrderService.orderSaleRank(record);
            result.put("result", osr);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 校验扫码所得优惠券是否适用所选订单
     *
     * @param saleOrder
     * @return 校验结果
     * @Author 路江
     */
    @RequestMapping(value = "/couponsCheckOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> couponsCheckOrder(@RequestBody SaleOrder saleOrder) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            result = saleOrderService.couponsCheckOrder(saleOrder);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 查看特定时间内下未付款的订单（30分钟，15分钟），设置取消订单
     *
     * @return
     * @author 路江
     */
    @RequestMapping(value = "/queryOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryOrder() {
        Map<String, Object> result = new HashMap<>(8);
        try {
            result = saleOrderService.queryOrder();
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 校验订单是否过来规定付款时间限定
     *
     * @param saleOrder
     * @return
     */
    @RequestMapping(value = "/checkOrderStatus", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> checkOrderStatus(@RequestBody SaleOrder saleOrder) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            result = saleOrderService.checkOrderStatus(saleOrder);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * api 订单upsert接口
     *
     * @param saleOrder
     * @return
     */
    @RequestMapping(value = "/apiOrderUpsert", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> apiOrderUpsert(@RequestBody ApiOrder saleOrder) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            Long rows = apiSaleOrderService.apiOrderUpsert(saleOrder);
            result.put("rows", rows);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("detailMessage", e.getMessage());
        }
        return result;
    }


    /**
     * 营销助手未登录状态下分享
     * @author 旷锐锋
     * @date 2019/2/21
     */
    @RequestMapping(value = "/notLogin/queryByExamplePage")
    @ResponseBody
    public Map<String, Object> query(@JsonParam SaleOrder saleOrder, @JsonParam QueryParams qps,
                                     HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {
            // 未登录状态下，模拟登录，处理特殊逻辑
            saleOrder.setImitateLogin("Y");
            result = super.queryByExamplePage(qps, saleOrder, session, request, response);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 根据录入结果生成相应订单
     * @author 姚江漪
     * @date 2019/08/17 15:03
     */
    @RequestMapping(value = "/genInteractionOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> genInteractionOrder(@RequestBody JSONObject jsonObject) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            saleOrderService.genInteractionOrder(jsonObject);
            result.put("result", "");
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 创建奖励订单头行记录和物流信息
     * @author 姚彭健
     * @date 2019/12/10
     */
    @RequestMapping({"/createRewardOrder"})
    @ResponseBody
    public Map<String, Object> createRewardOrder(@JsonParam SaleOrder entity, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<>(16);
        // 奖励订单的订单编号格式和ka订单一致
        KeyGenerateUtil keyGenerateUtil = KeyGenerateUtil.getInstance(jdbcTemplate);
        entity.setOrderNo(keyGenerateUtil.getOrderCode());
        // 根据奖励平台传来的奖励订单对象创建奖励订单头行记录、物流记录
        try {
            saleOrderService.createRewardOrder(entity);
            resultMap.put("success", true);
            resultMap.put("result", entity.getId());
        } catch (Exception e) {
            LCLogger.withException(e);
            resultMap.put("success", false);
            resultMap.put("result", e.getMessage());
        }
        return resultMap;
    }
}
